package com.gitee.xhs.util;

import com.gitee.xhs.dao.ModifyingPointDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.*;

import static com.gitee.xhs.StateConstant.CHECK_POINT_PREFIX;

/**
 * @author BigHead
 * @date 2022/7/11 14:49
 * @description SavePointApiUtil
 */
public class SavePointApiUtil {

    private static final Logger logger = LoggerFactory.getLogger(SavePointApiUtil.class);

    private static final String DIR_SPLIT = "\\\\";
    private static final String DIR_PREFIX = "_";
    private static final String NEW_SAVE_POINT_WRITER_JOB_NAME = "newSavePointWriter";
    private static final String NEW_SAVE_POINT_WRITER_JOB_NAME_PREFIX = NEW_SAVE_POINT_WRITER_JOB_NAME + DIR_PREFIX;

    public static final String MODIFYING_NAME = "modifying";
    private static final String MODIFYING_PREFIX = MODIFYING_NAME + DIR_PREFIX;

    /**
     * 合理生成 新Savepoint/CheckPoint文件夹
     *
     * @param baseFilePath 对应实验父文件夹
     * @return 已生成的文件夹
     */
    public static String getNewSavePointWriterJobPath(String baseFilePath) {
        int dirIndex = 0;
        String returnDir = baseFilePath + NEW_SAVE_POINT_WRITER_JOB_NAME_PREFIX;
        File baseDir = new File(baseFilePath);
        if (baseDir.isDirectory()) {
            // 循环任务名称
            for (File jobIdDir : Objects.requireNonNull(baseDir.listFiles())) {
                if (jobIdDir.isDirectory()) {
                    if (jobIdDir.getName().startsWith(NEW_SAVE_POINT_WRITER_JOB_NAME_PREFIX)) {
                        int tempDirIndex = Integer.parseInt(jobIdDir.getName().split(DIR_PREFIX)[1]);
                        if (dirIndex < tempDirIndex) {
                            dirIndex = tempDirIndex;
                        }
                    }
                }
            }
        }
        returnDir = returnDir + (dirIndex + 1);
        // 创建文件夹
        FileUtil.createDir(returnDir);
        return CHECK_POINT_PREFIX + returnDir;
    }


    /**
     * 获取待修改文件夹
     *
     * @param baseFilePath 对应实验父文件夹
     * @return ModifyingPointDao
     */
    public static ModifyingPointDao getModifyingPath(String baseFilePath) {
        Map<String, String> pathMap = FileUtil.listHasStateFilePath(baseFilePath);
        Optional<String> firstJobId = pathMap
                .keySet()
                .stream()
                .filter(jobId -> !jobId.startsWith(NEW_SAVE_POINT_WRITER_JOB_NAME))
                .filter(jobId -> !jobId.startsWith(MODIFYING_PREFIX))
                .sorted()
                .findFirst();

        Optional<Integer> maxInteger = pathMap
                .keySet()
                .stream()
                .filter(jobId -> jobId.startsWith(MODIFYING_PREFIX))
                .map(jobId -> jobId.split(DIR_PREFIX)[jobId.split(DIR_PREFIX).length - 1])
                .map(Integer::valueOf)
                .max(Comparator.naturalOrder());

        if (firstJobId.isPresent()) {
            String modifyingJobName = MODIFYING_PREFIX + firstJobId.get() + DIR_PREFIX + (maxInteger.map(integer -> integer + 1).orElse(1));
            boolean breakPath = false;
            List<String> reducePathList = new ArrayList<>();
            for (String pathString : pathMap.get(firstJobId.get()).split(DIR_SPLIT)) {
                if (breakPath) {
                    break;
                }
                if (pathString.equals(firstJobId.get())) {
                    breakPath = true;
                }
                reducePathList.add(pathString);
            }
            String modifyingPath = String.join(DIR_SPLIT, reducePathList).replace(firstJobId.get(), modifyingJobName);
            // 创建文件夹
            FileUtil.createDir(modifyingPath);
            return new ModifyingPointDao(
                    CHECK_POINT_PREFIX + pathMap.get(firstJobId.get()),
                    CHECK_POINT_PREFIX + modifyingPath
            );
        } else {
            logger.error(baseFilePath + ",无测试对应文件夹");
            System.exit(-1);
            return null;
        }
    }

}
